part of common_lib_plugin;

class DeviceType {
  static double devicePixelRatio = ui.PlatformDispatcher.instance.views.firstOrNull?.devicePixelRatio ?? 3.5;
  static Size size = ui.PlatformDispatcher.instance.views.first.physicalSize;
  static double width = size.width;
  static double height = size.height;
  final bool isTablet, isPhone, isIos, isAndroid;
  static DeviceType? _device;

  DeviceType({required this.isTablet, required this.isPhone, required this.isIos, required this.isAndroid});

  factory DeviceType.get() {
    if (_device != null) return _device!;

    bool isTablet;
    bool isPhone;
    bool isIos = Platform.isIOS;
    bool isAndroid = Platform.isAndroid;

    if (devicePixelRatio < 2 && (width >= 1000 || height >= 1000)) {
      isTablet = true;
      isPhone = false;
    } else if (devicePixelRatio == 2 && (width >= 1920 || height >= 1920)) {
      isTablet = true;
      isPhone = false;
    } else {
      isTablet = false;
      isPhone = true;
    }

    // Recalculate for Android Tablet using device inches
    if (isAndroid) {
      try {
        final adjustedWidth = _calWidth() / devicePixelRatio;
        final adjustedHeight = _calHeight() / devicePixelRatio;
        final diagonalSizeInches = (math.sqrt(math.pow(adjustedWidth, 2) + math.pow(adjustedHeight, 2))) / _ppi;
        //print("Dialog size inches is $diagonalSizeInches");
        if (diagonalSizeInches >= 7) {
          isTablet = true;
          isPhone = false;
        } else {
          isTablet = false;
          isPhone = true;
        }
      } catch (e) {
        logW('Device get $e');
      }
    }

    return _device = DeviceType(isTablet: isTablet, isPhone: isPhone, isAndroid: isAndroid, isIos: isIos);
  }

  static double _calWidth() {
    if (width > height) return (width + (ui.PlatformDispatcher.instance.views.first.viewPadding.left + ui.PlatformDispatcher.instance.views.first.viewPadding.right) * width / height);
    return (width + ui.PlatformDispatcher.instance.views.first.viewPadding.left + ui.PlatformDispatcher.instance.views.first.viewPadding.right);
  }

  static double _calHeight() {
    return (height + (ui.PlatformDispatcher.instance.views.first.viewPadding.top + ui.PlatformDispatcher.instance.views.first.viewPadding.bottom));
  }

  static int get _ppi => Platform.isAndroid
      ? 160
      : Platform.isIOS
          ? 150
          : 96;

  @override
  String toString() {
    return 'Device{isTablet: $isTablet, isPhone: $isPhone, isIos: $isIos, isAndroid: $isAndroid}';
  }
}
